using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Utility.Logger;
using System.Web;
using System.Xml;

namespace System
{
	public static class TypeExtension
	{
		private const int LOW_CHINESE = 19968;

		private const int HEIGHT_CHINESE = 40891;

		private static ConcurrentDictionary<Enum, string> _CacheDescriptions;

		static TypeExtension()
		{
			_CacheDescriptions = new ConcurrentDictionary<Enum, string>();
		}

		public static void AddRange<T>(this ICollection<T> @this, IEnumerable<T> values)
		{
			foreach (T value in values)
			{
				@this.Add(value);
			}
		}

		public static string AllMessage(this Exception ex)
		{
			string str;
			if (ex != null)
			{
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append(ex.Message);
				if (ex.InnerException != null)
				{
					stringBuilder.Append(Environment.NewLine);
					stringBuilder.Append(">").Append(AllMessage(ex.InnerException));
				}
				str = stringBuilder.ToString();
			}
			else
			{
				str = string.Empty;
			}
			return str;
		}

		public static void Append(this Stream stream, Stream descSream)
		{
			byte[] numArray = new byte[checked(descSream.Length)];
			descSream.Read(numArray, 0, (int)numArray.Length);
			descSream.Seek((long)0, SeekOrigin.Begin);
			stream.Write(numArray, 0, (int)numArray.Length);
		}

		public static void AppendKeyValue(this StringBuilder builder, string key, object value, string end = " ")
		{
			if ((value == null ? false : !IsInvalid(value.ToString())))
			{
				builder.AppendFormat("{0}：{1}{2}", key, value, end);
			}
		}

		public static void AppendKeyValue(this StringBuilder sb, string key, Enum value, string end = " ")
		{
			sb.Append(key).Append("：").Append(GetDescription(value)).Append(end);
		}

		public static void AppendKeyValueNewLine(this StringBuilder sb, string key, object value)
		{
			if ((value == null ? false : !IsInvalid(value.ToString())))
			{
				sb.Append(key).Append("：").Append(value).Append(Environment.NewLine);
			}
		}

		public static void AppendKeyValueNewLine(this StringBuilder sb, string key, Enum value)
		{
			sb.Append(key).Append("：").Append(GetDescription(value)).Append(Environment.NewLine);
		}

		public static bool Contains(this string value, string match, StringComparison comparison)
		{
			return value.IndexOf(match, comparison) > -1;
		}

		public static IEnumerable<Ttarget> ConvertAll<Ttarget>(this IEnumerable @this)
		where Ttarget : class
		{
			IEnumerable<Ttarget> ttargets;
			if (@this != null)
			{
				IEnumerable<Ttarget> ttargets1 = @this as IEnumerable<Ttarget>;
				if (ttargets1 == null)
				{
					Collection<Ttarget> ttargets2 = new Collection<Ttarget>();
					foreach (object thi in @this)
					{
						Ttarget ttarget = (Ttarget)(thi as Ttarget);
						if (ttarget == null)
						{
							throw new ArgumentException(string.Concat("invalid Target:", typeof(Ttarget)));
						}
						ttargets2.Add(ttarget);
					}
					ttargets = ttargets2;
				}
				else
				{
					ttargets = ttargets1;
				}
			}
			else
			{
				ttargets = null;
			}
			return ttargets;
		}

		public static IEnumerable<Ttarget> ConvertAllyield<Ttarget>(this IEnumerable @this)
		where Ttarget : class
		{
			if (@this != null)
			{
				foreach (object thi in @this)
				{
					yield return (Ttarget)(thi as Ttarget);
				}
			}
		}

		public static T Copy<T>(this T obj)
		where T : class
		{
			T t;
			MemoryStream memoryStream = new MemoryStream();
			try
			{
				BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
				binaryFormatter.Serialize(memoryStream, obj);
				memoryStream.Seek((long)0, SeekOrigin.Begin);
				T t1 = default(T);
				try
				{
					t1 = (T)binaryFormatter.Deserialize(memoryStream);
				}
				catch (Exception exception)
				{
					LogHelper.Error("深拷贝对象失败", exception);
				}
				t = t1;
			}
			finally
			{
				if (memoryStream != null)
				{
					((IDisposable)memoryStream).Dispose();
				}
			}
			return t;
		}

		private static object Copy1(this object obj)
		{
			object obj1;
			Type type = obj.GetType();
			if (!type.IsValueType)
			{
				obj1 = Activator.CreateInstance(type);
				MemberInfo[] members = obj.GetType().GetMembers();
				for (int i = 0; i < (int)members.Length; i++)
				{
					MemberInfo memberInfo = members[i];
					if (memberInfo.MemberType == MemberTypes.Field)
					{
						FieldInfo fieldInfo = (FieldInfo)memberInfo;
						object value = fieldInfo.GetValue(obj);
						if (!(value is ICloneable))
						{
							fieldInfo.SetValue(obj1, Copy(value));
						}
						else
						{
							fieldInfo.SetValue(obj1, (value as ICloneable).Clone());
						}
					}
					else if (memberInfo.MemberType == MemberTypes.Property)
					{
						PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
						if (propertyInfo.GetSetMethod(false) != null)
						{
							object value1 = propertyInfo.GetValue(obj, null);
							if (!(value1 is ICloneable))
							{
								propertyInfo.SetValue(obj1, Copy(value1), null);
							}
							else
							{
								propertyInfo.SetValue(obj1, (value1 as ICloneable).Clone(), null);
							}
						}
					}
				}
			}
			else
			{
				obj1 = obj;
			}
			return obj1;
		}

		public static object CreateInstance(this Type @this)
		{
			object obj;
			try
			{
				obj = Activator.CreateInstance(@this);
			}
			catch
			{
				obj = null;
			}
			return obj;
		}

		public static string Encode(this string value, Encoding encode)
		{
			Guard.ArgumentNotNull(value, "value");
			Encoding unicode = Encoding.Unicode;
			byte[] numArray = Encoding.Convert(unicode, encode, ToBytes(value, unicode));
			return GetString(numArray, encode);
		}

		public static string Encode(this string value, Encoding sencode, Encoding tencode)
		{
			Guard.ArgumentNotNull(value, "value");
			byte[] numArray = Encoding.Convert(sencode, tencode, ToBytes(value, sencode));
			return GetString(numArray, tencode);
		}

		public static T FindFirst<T>(this IEnumerable<T> source)
		where T : class
		{
			T current;
			T t;
			if (!IsInvalid(source))
			{
				IEnumerator<T> enumerator = source.GetEnumerator();
				try
				{
					if (enumerator.MoveNext())
					{
						current = enumerator.Current;
						return current;
					}
				}
				finally
				{
					if (enumerator != null)
					{
						enumerator.Dispose();
					}
				}
				t = default(T);
				current = t;
			}
			else
			{
				t = default(T);
				current = t;
			}
			return current;
		}

		public static object FindFirst(this IEnumerable source)
		{
			object current;
			if (!IsInvalid(source))
			{
				IEnumerator enumerator = source.GetEnumerator();
				try
				{
					if (enumerator.MoveNext())
					{
						current = enumerator.Current;
						return current;
					}
				}
				finally
				{
					IDisposable disposable = enumerator as IDisposable;
					if (disposable != null)
					{
						disposable.Dispose();
					}
				}
				current = null;
			}
			else
			{
				current = null;
			}
			return current;
		}

		public static void ForEach<T>(this IEnumerable<T> souce, Action<T> action)
		{
			if (!IsInvalid(souce))
			{
				foreach (T t in souce)
				{
					action(t);
				}
			}
		}

		public static string Format(this string @this, object arg0)
		{
			return string.Format(@this, arg0);
		}

		public static string Format(this string @this, object arg0, object arg1)
		{
			return string.Format(@this, arg0, arg1);
		}

		public static string Format(this string @this, object arg0, object arg1, object arg2)
		{
			return string.Format(@this, arg0, arg1, arg2);
		}

		public static string Format(this string @this, params object[] arg0)
		{
			return string.Format(@this, arg0);
		}

		public static string GetDescription(this Enum @this)
		{
			string orAdd = _CacheDescriptions.GetOrAdd(@this, (Enum key) => {
				FieldInfo field = key.GetType().GetField(key.ToString());
				return (field == null ? GetDescriptions(key, ",") : GetDescription(field));
			});
			return orAdd;
		}

		private static string GetDescription(FieldInfo field)
		{
			Attribute customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false);
			return (customAttribute == null ? string.Empty : ((DescriptionAttribute)customAttribute).Description);
		}

		public static string GetDescriptions(this Enum @this, string separator = ",")
		{
			string[] strArrays = @this.ToString().Split(new char[] { ',' });
			string[] description = new string[(int)strArrays.Length];
			Type type = @this.GetType();
			for (int i = 0; i < (int)strArrays.Length; i++)
			{
				FieldInfo field = type.GetField(strArrays[i].Trim());
				if (!(field == null))
				{
					description[i] = GetDescription(field);
				}
			}
			return string.Join(separator, description);
		}

		public static string GetEnumNameByValue<T>(this object value)
		{
			Type type = typeof(T);
			if (!type.IsEnum)
			{
				throw new InvalidCastException("必须是枚举类型才能获取枚举名称。");
			}
			return Enum.GetName(type, value);
		}

		public static Type GetNullableGenericType(this Type type)
		{
			return (IsNullableType(type) ? type.GetGenericArguments()[0] : type);
		}

		public static string GetPropertyName<T>(this Expression<Func<T, object>> expr)
		{
			return ((MemberExpression)expr.Body).Member.Name;
		}

		public static TEnum GetSafeAttributeEnum<TEnum>(this XmlNode node, string attribute, TEnum defaultValue)
		{
			TEnum @enum;
			try
			{
				string safeAttributeValue = GetSafeAttributeValue(node, attribute);
				if (IsValid(safeAttributeValue))
				{
					@enum = ToEnum<TEnum>(safeAttributeValue.Replace("，", ","));
					return @enum;
				}
			}
			catch
			{
			}
			@enum = defaultValue;
			return @enum;
		}

		public static string GetSafeAttributeValue(this XmlNode node, string attribute)
		{
			string empty;
			if (node == null)
			{
				empty = string.Empty;
			}
			else if (node.Attributes == null)
			{
				empty = string.Empty;
			}
			else
			{
				XmlAttribute itemOf = node.Attributes[attribute];
				empty = (itemOf != null ? itemOf.Value.Trim() : string.Empty);
			}
			return empty;
		}

		public static TValue GetSafeValue<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue defalut)
		{
			TValue tValue;
			if (!IsInvalid(dictionary))
			{
				tValue = (!dictionary.ContainsKey(key) ? defalut : dictionary[key]);
			}
			else
			{
				tValue = defalut;
			}
			return tValue;
		}

		public static T GetSafeValue<T>(this IList<T> @this, int index, T defaultValue)
		{
			T t;
			if (!IsInvalid(@this))
			{
				t = (@this.Count <= index ? @this[index] : defaultValue);
			}
			else
			{
				t = defaultValue;
			}
			return t;
		}

		public static string GetString(this byte[] bytes, Encoding encode)
		{
			string str;
			str = ((bytes == null ? false : Enumerable.Count(bytes) > 0) ? encode.GetString(bytes) : string.Empty);
			return str;
		}

		public static string GetString(this byte[] bytes)
		{
			return GetString(bytes, Encoding.Default);
		}

		public static object GetValue(this PropertyInfo pi, object obj)
		{
			object obj1;
			if ((pi == null ? false : obj != null))
			{
				MethodInfo getMethod = pi.GetGetMethod();
				obj1 = (!(getMethod == null) ? getMethod.Invoke(obj, Constants.EmptyObjectArray) : null);
			}
			else
			{
				obj1 = null;
			}
			return obj1;
		}

		public static bool Has(this Enum value, Enum target)
		{
			bool flag;
			Guard.ArgumentNotNull(value, "Enum value");
			Guard.ArgumentNotNull(target, "Enum target");
			flag = (!(value.GetType() != target.GetType()) ? (value.GetHashCode() & target.GetHashCode()) == target.GetHashCode() : false);
			return flag;
		}

		public static string HtmlDecode(this string source)
		{
			string str;
			str = (string.IsNullOrEmpty(source) ? string.Empty : HttpUtility.HtmlDecode(source));
			return str;
		}

		public static string HtmlEncode(this string source)
		{
			string str;
			str = (string.IsNullOrEmpty(source) ? string.Empty : HttpUtility.HtmlEncode(source));
			return str;
		}

		public static bool IsBetween<T>(this T @this, T lower, T upper, bool includeLower = true, bool includeUpper = true)
		where T : IComparable<T>
		{
			bool flag;
			bool flag1;
			if (@this != null)
			{
				int num = @this.CompareTo(lower);
				int num1 = @this.CompareTo(upper);
				if ((!includeLower || num != 0) && (!includeUpper || num1 != 0))
				{
					flag1 = (num <= 0 ? false : num1 < 0);
				}
				else
				{
					flag1 = true;
				}
				flag = flag1;
			}
			else
			{
				flag = false;
			}
			return flag;
		}

		public static bool IsBetween<T>(this T @this, T lower, T upper, IComparer<T> comparer, bool includeLower = true, bool includeUpper = true)
		{
			bool flag;
			bool flag1;
			if (@this != null)
			{
				int num = comparer.Compare(@this, lower);
				int num1 = comparer.Compare(@this, upper);
				if ((!includeLower || num != 0) && (!includeUpper || num1 != 0))
				{
					flag1 = (num <= 0 ? false : num1 < 0);
				}
				else
				{
					flag1 = true;
				}
				flag = flag1;
			}
			else
			{
				flag = false;
			}
			return flag;
		}

		public static bool IsChinese(this char value)
		{
			return (value < '\u4E00' ? false : value <= '\u9FBB');
		}

		public static bool IsCompatibleType(this Type type1, Type type2)
		{
			bool flag;
			if (type1 == type2)
			{
				flag = true;
			}
			else if ((!type1.IsEnum ? true : !(Enum.GetUnderlyingType(type1) == type2)))
			{
				Type underlyingType = Nullable.GetUnderlyingType(type1);
				Type type = Nullable.GetUnderlyingType(type2);
				flag = ((underlyingType == null ? true : !(type != null)) ? false : IsCompatibleType(underlyingType, type));
			}
			else
			{
				flag = true;
			}
			return flag;
		}

		public static bool IsGreaterThanZero(this int value)
		{
			return value > 0;
		}

		public static bool IsGreaterThanZero(this int? value)
		{
			bool flag;
			if (value.HasValue)
			{
				int? nullable = value;
				flag = (nullable.GetValueOrDefault() <= 0 ? false : nullable.HasValue);
			}
			else
			{
				flag = false;
			}
			return flag;
		}

		public static bool IsHasChinese(this string value)
		{
			bool flag = Enumerable.Any(value, (char c) => IsChinese(c));
			return flag;
		}

		public static bool IsImplementsInterface(this Type objectType, Type interfaceType)
		{
			bool flag;
			if (!interfaceType.IsInterface)
			{
				throw new ArgumentException(string.Format("查找类似 指定的类型{0}不是接口类型。", interfaceType.Name), "interfaceType");
			}
			Type[] interfaces = objectType.GetInterfaces();
			int num = 0;
			while (true)
			{
				if (num < (int)interfaces.Length)
				{
					Type type = interfaces[num];
					if (!(type == interfaceType))
					{
						if (type.Name.Contains("`"))
						{
							if ((type.Name != interfaceType.Name ? false : type.Assembly == interfaceType.Assembly))
							{
								flag = true;
								break;
							}
						}
						num++;
					}
					else
					{
						flag = true;
						break;
					}
				}
				else
				{
					flag = false;
					break;
				}
			}
			return flag;
		}

		public static bool IsInstanceOfT<T>(this Type instanceType)
		{
			return instanceType.IsInstanceOfType(typeof(T));
		}

		public static bool IsInstanceOfT<T>(this object instance)
		{
			bool flag;
			flag = (instance != null ? instance.GetType().IsInstanceOfType(typeof(T)) : false);
			return flag;
		}

		public static bool IsInstanceOfType(this Type instanceType, Type type)
		{
			bool flag;
			if (!(instanceType == type))
			{
				Type[] interfaces = instanceType.GetInterfaces();
				int num = 0;
				while (num < (int)interfaces.Length)
				{
					if (!(interfaces[num] == type))
					{
						num++;
					}
					else
					{
						flag = true;
						return flag;
					}
				}
				while (instanceType != Constants.ObjectType)
				{
					if (!(type == instanceType))
					{
						instanceType = instanceType.BaseType;
					}
					else
					{
						flag = true;
						return flag;
					}
				}
				flag = false;
			}
			else
			{
				flag = true;
			}
			return flag;
		}

		public static bool IsInstanceOfType(this object instance, Type type)
		{
			bool flag;
			flag = (instance != null ? instance.GetType().IsInstanceOfType(type) : false);
			return flag;
		}

		public static bool IsInvalid<T>(this IEnumerable<T> source)
		{
			return !IsValid(source);
		}

		public static bool IsInvalid(this IEnumerable @this)
		{
			return !IsValid(@this);
		}

		public static bool IsInvalid(this string value)
		{
			return IsNullOrEmptyOrWhiteSpace(value);
		}

		public static bool IsMatch(this string source, string pattern, RegexOptions options)
		{
			bool flag;
			flag = (!IsInvalid(source) ? Regex.IsMatch(source, pattern, options) : false);
			return flag;
		}

		public static bool IsMatch(this string source, string pattern)
		{
			bool flag;
			flag = (!IsInvalid(source) ? IsMatch(source, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline) : false);
			return flag;
		}

		public static bool IsNullableType(this Type type)
		{
			return (!type.IsGenericType ? false : type.GetGenericTypeDefinition() == Constants.NullableType);
		}

		public static bool IsNullOrEmpty(this string value)
		{
			return string.IsNullOrEmpty(value);
		}

		public static bool IsNullOrEmptyOrWhiteSpace(this string value)
		{
			bool flag = IsNullOrEmpty(value);
			if (!flag)
			{
				flag = IsNullOrEmpty(value.Trim());
			}
			return flag;
		}

		public static bool IsValid(this Version value)
		{
			bool flag;
			if (!(value == null))
			{
				flag = (value.Major > 0 || value.Minor > 0 || value.Build > 0 ? true : value.Revision > 0);
			}
			else
			{
				flag = false;
			}
			return flag;
		}

		public static bool IsValid(this DateTime value)
		{
			return ((DateTime.MinValue == value ? false : !(DateTime.MaxValue == value)) ? true : false);
		}

		public static bool IsValid(this DateTime? value)
		{
			bool flag;
			bool flag1;
			if (value.HasValue)
			{
				DateTime minValue = DateTime.MinValue;
				DateTime? nullable = value;
				if ((!nullable.HasValue ? false : minValue == nullable.GetValueOrDefault()))
				{
					flag1 = false;
					flag = (flag1 ? true : false);
					return flag;
				}
				minValue = DateTime.MaxValue;
				nullable = value;
				flag1 = (!nullable.HasValue ? true : minValue == nullable.GetValueOrDefault()) == true;
				flag = (flag1 ? true : false);
				return flag;
			}
			flag1 = false;
			flag = (flag1 ? true : false);
			return flag;
		}

		public static bool IsValid<T>(this IEnumerable<T> source)
		{
			return (source == null ? false : Enumerable.Any(source));
		}

		public static bool IsValid(this IEnumerable @this)
		{
			bool flag;
			if (@this != null)
			{
				IEnumerator enumerator = @this.GetEnumerator();
				try
				{
					if (enumerator.MoveNext())
					{
						object current = enumerator.Current;
						flag = true;
						return flag;
					}
				}
				finally
				{
					IDisposable disposable = enumerator as IDisposable;
					if (disposable != null)
					{
						disposable.Dispose();
					}
				}
				flag = false;
			}
			else
			{
				flag = false;
			}
			return flag;
		}

		public static bool IsValid(this string value)
		{
			return !IsNullOrEmptyOrWhiteSpace(value);
		}

		public static Match Match(this string source, string pattern)
		{
			Match match = Match(source, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
			return match;
		}

		public static Match Match(this string source, string pattern, RegexOptions options)
		{
			return Regex.Match(source, pattern, options);
		}

		public static T Remove<T>(this Enum value, Enum target)
		{
			Guard.ArgumentNotNull(value, "Enum value");
			Guard.ArgumentNotNull(target, "Enum target");
			int hashCode = value.GetHashCode() & ~target.GetHashCode();
			return ToEnum<T>(hashCode);
		}

		public static T SafeValue<T>(this Nullable<T> @this)
		where T : struct
		{
			Nullable<T> nullable = @this;
			return (nullable.HasValue ? nullable.GetValueOrDefault() : default(T));
		}

		public static string To16Bland(this byte value)
		{
			return value.ToString("X2");
		}

		public static string To16Bland(this byte[] values, string separator = " ")
		{
			string str;
			if ((values == null ? false : (int)values.Length > 0))
			{
				StringBuilder stringBuilder = new StringBuilder();
				byte[] numArray = values;
				for (int i = 0; i < (int)numArray.Length; i++)
				{
					byte num = numArray[i];
					stringBuilder.Append(To16Bland(num)).Append(separator);
				}
				str = stringBuilder.ToString();
			}
			else
			{
				str = string.Empty;
			}
			return str;
		}

		public static byte[] ToASCIIBytes(this string value)
		{
			return ToBytes(value, Encoding.ASCII);
		}

		public static string ToBinary(this byte value)
		{
			return Convert.ToString(value, 2);
		}

		public static string ToBinary(this byte[] values, string separator = " ")
		{
			string str;
			if ((values == null ? false : (int)values.Length > 0))
			{
				StringBuilder stringBuilder = new StringBuilder();
				byte[] numArray = values;
				for (int i = 0; i < (int)numArray.Length; i++)
				{
					byte num = numArray[i];
					stringBuilder.Append(ToBinary(num)).Append(separator);
				}
				str = stringBuilder.ToString();
			}
			else
			{
				str = string.Empty;
			}
			return str;
		}

		public static bool ToBoolean(this string value)
		{
			bool flag;
			if (!bool.TryParse(value, out flag))
			{
				throw new InvalidCastException(string.Concat("\"", value, "\"不是有效的boolean，请确认。"));
			}
			return flag;
		}

		public static byte ToByte(this int value)
		{
			byte bytes;
			try
			{
				bytes = BitConverter.GetBytes(value)[0];
			}
			catch
			{
				bytes = 0;
			}
			return bytes;
		}

		public static byte[] ToBytes(this string value, Encoding encode)
		{
			return encode.GetBytes(value);
		}

		public static byte[] ToBytes(this string value)
		{
			return ToBytes(value, Encoding.Default);
		}

		public static string ToCNString(this bool value)
		{
			return (value ? "是" : "否");
		}

		public static string ToCNString(this bool? value)
		{
			return (value.HasValue ? value.ToString() : string.Empty);
		}

		public static string ToDateString(this DateTime value)
		{
			return (IsValid(value) ? value.ToString("yyyy-MM-dd") : string.Empty);
		}

		public static string ToDateString(this DateTime? value)
		{
			string empty;
			if (!value.HasValue)
			{
				empty = string.Empty;
			}
			else
			{
				empty = (IsValid(value) ? value.Value.ToString("yyyy-MM-dd") : string.Empty);
			}
			return empty;
		}

		public static string ToDateString(this DateTime? value, string format, string defaultStr = "")
		{
			string str;
			if (!value.HasValue)
			{
				str = defaultStr;
			}
			else
			{
				str = (IsValid(value) ? value.Value.ToString(format) : defaultStr);
			}
			return str;
		}

		public static string ToDateStringFromNow(this DateTime dt)
		{
			string empty;
			if (IsValid(dt))
			{
				TimeSpan now = DateTime.Now - dt;
				if (now.TotalDays > 365)
				{
					empty = string.Format("{0}年前", (int)Math.Floor(now.TotalDays / 365));
				}
				else if (now.TotalDays > 30)
				{
					empty = string.Format("{0}个月前", (int)Math.Floor(now.TotalDays / 30));
				}
				else if (now.TotalDays > 7)
				{
					empty = string.Format("{0}周前", (int)Math.Floor(now.TotalDays / 7));
				}
				else if (now.TotalDays > 1)
				{
					empty = string.Format("{0}天前", (int)Math.Floor(now.TotalDays));
				}
				else if (now.TotalHours > 1)
				{
					empty = string.Format("{0}小时前", (int)Math.Floor(now.TotalHours));
				}
				else if (now.TotalMinutes > 1)
				{
					empty = string.Format("{0}分钟前", (int)Math.Floor(now.TotalMinutes));
				}
				else if (now.TotalSeconds >= 1)
				{
					empty = string.Format("{0}秒前", (int)Math.Floor(now.TotalSeconds));
				}
				else if (!(dt.Date == DateTime.Now.Date))
				{
					now = dt - DateTime.Now;
					int num = (int)Math.Floor(Math.Abs(now.TotalDays));
					if (num == 1)
					{
						empty = "明天";
					}
					else if (num == 2)
					{
						empty = "后天";
					}
					else if (num < 7)
					{
						empty = string.Format("{0}天后", num);
					}
					else if (num >= 30)
					{
						empty = (num >= 365 ? string.Format("{0}年后", num / 365) : string.Format("{0}月后", num / 30));
					}
					else
					{
						empty = string.Format("{0}周后", num / 7);
					}
				}
				else
				{
					empty = "今天";
				}
			}
			else
			{
				empty = string.Empty;
			}
			return empty;
		}

		public static string ToDateStringFromNow(this DateTime? dt)
		{
			string str;
			str = (!dt.HasValue ? string.Empty : ToDateStringFromNow(dt.Value));
			return str;
		}

		public static DateTime ToDateTime(this string value, string format, string culture = "zh-CHS")
		{
			DateTime dateTime;
			if (!DateTime.TryParseExact(value, format, new CultureInfo("zh-CHS"), DateTimeStyles.None, out dateTime))
			{
				throw new Exception(string.Format("字符串（{0}）不能按照格式（{1}）解析为日期时间", value, format));
			}
			return dateTime;
		}

		public static DateTime ToDateTime(this string dateTime)
		{
			DateTime dateTime1;
			if (!DateTime.TryParse(dateTime, out dateTime1))
			{
				throw new InvalidCastException(string.Concat("\"", dateTime, "\"不是有效的时间格式，请确认。"));
			}
			return dateTime1;
		}

		public static string ToDateTimeString(this DateTime value)
		{
			string empty;
			if (IsValid(value))
			{
				empty = ((value.Hour != 0 || value.Minute != 0 ? true : value.Second != 0) ? value.ToString("yyyy-MM-dd HH:mm:ss") : ToDateString(value));
			}
			else
			{
				empty = string.Empty;
			}
			return empty;
		}

		public static string ToDateTimeString(this DateTime? value)
		{
			string str;
			str = (!IsValid(value) ? string.Empty : ToDateTimeString(value.Value));
			return str;
		}

		public static decimal ToDecimal(this string value)
		{
			decimal num;
			if (!decimal.TryParse(value, out num))
			{
				throw new InvalidCastException(string.Concat("不能将字符串\"", value, "\"转换为Decimal数字。"));
			}
			return num;
		}

		public static Dictionary<string, string> ToDictionaryH(this HttpContext context)
		{
			Dictionary<string, string> strs;
			if ((context == null ? false : context.Request != null))
			{
				string httpMethod = context.Request.HttpMethod;
				NameValueCollection nameValueCollection = new NameValueCollection();
				if (httpMethod.Equals(GetDescription(EnumHttpMode.Post)))
				{
					nameValueCollection = context.Request.Form;
				}
				else if (httpMethod.Equals(GetDescription(EnumHttpMode.Get)))
				{
					nameValueCollection = context.Request.QueryString;
				}
				Dictionary<string, string> strs1 = new Dictionary<string, string>();
				if ((nameValueCollection == null ? false : nameValueCollection.Count > 0))
				{
					foreach (string str in nameValueCollection)
					{
						strs1.Add(str, nameValueCollection[str]);
					}
				}
				strs = strs1;
			}
			else
			{
				strs = new Dictionary<string, string>();
			}
			return strs;
		}

		public static double ToDouble(this string value)
		{
			double num;
			if (!double.TryParse(value, out num))
			{
				throw new InvalidCastException(string.Concat("不能将字符串\"", value, "\"转换为double数字。"));
			}
			return num;
		}

		public static dynamic ToDynamic(this IDataReader reader)
		{
			object expandoObjects;
			if (reader != null)
			{
				int fieldCount = reader.FieldCount;
				if (fieldCount > 0)
				{
					DynamicX dynamicX = new DynamicX();
					try
					{
						for (int i = 0; i < fieldCount; i++)
						{
							string name = reader.GetName(i);
							if ((name.Equals("new") ? true : name.StartsWith("_")))
							{
								name = name.Insert(0, "xly");
							}
							object value = null;
							try
							{
								value = reader.GetValue(i);
							}
							catch
							{
							}
							dynamicX.TrySetMember(new SetPropertyBinder(name), value);
						}
					}
					catch
					{
					}
					expandoObjects = dynamicX;
				}
				else
				{
					expandoObjects = new ExpandoObject();
				}
			}
			else
			{
				expandoObjects = new ExpandoObject();
			}
			return expandoObjects;
		}

		public static List<dynamic> ToDynamicCollection(this DataTable dt)
		{
			List<object> objs;
			if ((dt == null || dt.Rows.Count <= 0 ? false : dt.Columns.Count > 0))
			{
				List<object> objs1 = new List<object>();
				foreach (DataRow row in dt.Rows)
				{
					dynamic expandoObjects = new ExpandoObject();
					foreach (DataColumn column in dt.Columns)
					{
						((IDictionary<string, object>)expandoObjects)[column.ColumnName] = row[column];
						objs1.Add(expandoObjects);
					}
				}
				objs = objs1;
			}
			else
			{
				objs = new List<object>();
			}
			return objs;
		}

		public static T ToEnum<T>(this string name)
		{
			if (!typeof(T).IsEnum)
			{
				throw new InvalidCastException("必须是枚举类型才能转换。");
			}
			return (T)Enum.Parse(typeof(T), name, true);
		}

		public static T ToEnum<T>(this int value)
		{
			return ToEnum<T>(value.ToString());
		}

		public static T ToEnum<T>(this string[] values)
		{
			Guard.ArgumentNotNull(values, "values");
			if (!typeof(T).IsEnum)
			{
				throw new InvalidCastException("必须是枚举类型才能转换。");
			}
			List<string> strs = new List<string>();
			string[] strArrays = values;
			for (int i = 0; i < (int)strArrays.Length; i++)
			{
				T @enum = ToEnum<T>(strArrays[i]);
				strs.Add(@enum.ToString());
			}
			T t = ToEnum<T>(string.Join(",", strs.ToArray()));
			return t;
		}

		public static T ToEnumByValue<T>(this object value)
		{
			return ToEnum<T>(GetEnumNameByValue<T>(value));
		}

		public static int ToInt(this string value)
		{
			int num;
			if (!int.TryParse(value, out num))
			{
				throw new InvalidCastException(string.Concat("不能将字符串\"", value, "\"转换为整形数字。"));
			}
			return num;
		}

		public static short ToInt16(this string value)
		{
			short num;
			if (!short.TryParse(value, out num))
			{
				throw new InvalidCastException(string.Concat("不能将字符串\"", value, "\"转换为短整形数字。"));
			}
			return num;
		}

		public static long ToInt64(this string value)
		{
			long num;
			if (!long.TryParse(value, out num))
			{
				throw new InvalidCastException(string.Concat("不能将字符串\"", value, "\"转换为长整形数字。"));
			}
			return num;
		}

		public static List<T> ToList<T>(this IEnumerator<T> source)
		{
			List<T> ts;
			List<T> ts1 = new List<T>();
			if (source != null)
			{
				while (source.MoveNext())
				{
					ts1.Add(source.Current);
				}
				ts = ts1;
			}
			else
			{
				ts = ts1;
			}
			return ts;
		}

		public static string ToLogString(this Exception ex)
		{
			string str;
			if (ex != null)
			{
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append("  >>异常消息（Message）：").AppendLine(ex.Message);
				stringBuilder.Append("  >>异常来源（Source）：").AppendLine(ex.Source);
				stringBuilder.Append("  >>异常类型（ExceptionType）：").AppendLine(ex.GetType().ToString());
				stringBuilder.Append("  >>原生异常类型（BaseExceptionType）：").AppendLine(ex.GetBaseException().GetType().ToString());
				stringBuilder.Append("  >>出错的方法签名（TargetSite）：").Append(ex.TargetSite);
				if (ex.Data.Count > 0)
				{
					stringBuilder.Append(Environment.NewLine);
					stringBuilder.Append("  >>自定义数据（Data）：");
					StringBuilder stringBuilder1 = new StringBuilder();
					foreach (DictionaryEntry datum in ex.Data)
					{
						object[] key = new object[] { "Key：", datum.Key, "，Value：", datum.Value, "; " };
						stringBuilder1.Append(string.Concat(key));
					}
					stringBuilder.Append(stringBuilder1);
				}
				if (!string.IsNullOrEmpty(ex.StackTrace))
				{
					stringBuilder.Append(Environment.NewLine);
					stringBuilder.Append("  >>堆栈信息（StackTrace）：");
					stringBuilder.Append(Environment.NewLine);
					stringBuilder.Append(ex.StackTrace);
				}
				if (ex.InnerException != null)
				{
					stringBuilder.Append(Environment.NewLine);
					stringBuilder.Append(">>========================== 内部异常（InnerException）==========================");
					stringBuilder.Append(Environment.NewLine);
					stringBuilder.Append(ToLogString(ex.InnerException));
				}
				str = stringBuilder.ToString();
			}
			else
			{
				str = string.Empty;
			}
			return str;
		}

		public static string ToReverse(this string obj)
		{
			char[] charArray = obj.ToCharArray();
			Array.Reverse(charArray);
			return new string(charArray);
		}

		public static bool ToSafeBoolean(this string value, bool defaultValue = false)
		{
			bool flag;
			bool flag1;
			flag1 = (!bool.TryParse(value, out flag) ? defaultValue : flag);
			return flag1;
		}

		public static byte ToSafeByte(this string value)
		{
			byte num;
			byte num1;
			if (!byte.TryParse(value, out num))
			{
				num1 = 0;
			}
			else
			{
				num1 = num;
			}
			return num1;
		}

		public static DateTime? ToSafeDateTime(this string dateTime)
		{
			DateTime dateTime1;
			DateTime? nullable;
			if (!DateTime.TryParse(dateTime, out dateTime1))
			{
				nullable = null;
			}
			else
			{
				nullable = new DateTime?(dateTime1);
			}
			return nullable;
		}

		public static decimal ToSafeDecimal(this string value)
		{
			decimal num;
			decimal num1;
			num1 = (!decimal.TryParse(value, out num) ? new decimal(0) : num);
			return num1;
		}

		public static double ToSafeDouble(this string value)
		{
			double num;
			double num1;
			num1 = (!double.TryParse(value, out num) ? 0 : num);
			return num1;
		}

		public static T ToSafeEnum<T>(this string value, T defaultValue)
		{
			T @enum;
			try
			{
				@enum = ToEnum<T>(value);
			}
			catch
			{
				@enum = defaultValue;
			}
			return @enum;
		}

		public static int ToSafeInt(this string value)
		{
			int num;
			int safeDouble;
			if (!value.Contains(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator))
			{
				safeDouble = (!int.TryParse(value, out num) ? 0 : num);
			}
			else
			{
				safeDouble = (int)ToSafeDouble(value);
			}
			return safeDouble;
		}

		public static short ToSafeInt16(this string value)
		{
			short num;
			short num1;
			if (!short.TryParse(value, out num))
			{
				num1 = 0;
			}
			else
			{
				num1 = num;
			}
			return num1;
		}

		public static long ToSafeInt64(this string value)
		{
			long num;
			long safeDouble;
			if (!value.Contains(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator))
			{
				safeDouble = (!long.TryParse(value, out num) ? (long)0 : num);
			}
			else
			{
				safeDouble = (long)ToSafeDouble(value);
			}
			return safeDouble;
		}

		public static string ToSafeString(this object obj)
		{
			string str;
			str = (obj != null ? obj.ToString() : string.Empty);
			return str;
		}

		public static ulong ToSafeUlong(this string value)
		{
			ulong num;
			ulong safeDouble;
			if (string.IsNullOrWhiteSpace(value))
			{
				safeDouble = (ulong)0;
			}
			else if (value.Contains(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator))
			{
				safeDouble = (ulong)ToSafeDouble(value);
			}
			else if (!ulong.TryParse(value, out num))
			{
				safeDouble = (ulong)0;
			}
			else
			{
				safeDouble = num;
			}
			return safeDouble;
		}

		public static Version ToSafeVersion(this string value)
		{
			Version version;
			Version version1 = new Version();
			if (IsInvalid(value))
			{
				version = version1;
			}
			else if (!Version.TryParse(value, out version1))
			{
				MatchCollection matchCollections = Regex.Matches(value, "(\\d{1,8}\\.){1,3}\\d{1,8}", RegexOptions.IgnoreCase);
				version = (matchCollections.Count != 0 ? ToSafeVersion(ToSafeString(matchCollections[0])) : version1);
			}
			else
			{
				version = version1;
			}
			return version;
		}

		public static string ToShortString(this Version value)
		{
			string empty;
			if (!IsValid(value))
			{
				empty = string.Empty;
			}
			else if (!(value.Minor > 0 || value.Build > 0 ? true : value.Revision > 0))
			{
				empty = string.Format("{0}", value.Major);
			}
			else if (!(value.Build > 0 ? true : value.Revision > 0))
			{
				empty = string.Format("{0}.{1}", value.Major, value.Minor);
			}
			else if (value.Revision > 0)
			{
				object[] major = new object[] { value.Major, value.Minor, value.Build, value.Revision };
				empty = string.Format("{0}.{1}.{2}.{3}", major);
			}
			else
			{
				empty = string.Format("{0}.{1}.{2}", value.Major, value.Minor, value.Build);
			}
			return empty;
		}

		public static DateTime? ToUTCTime(this string dateTime)
		{
			DateTime? safeDateTime;
			DateTime? nullable = ToSafeDateTime(dateTime);
			if (!nullable.HasValue)
			{
				Regex regex = new Regex("(?i)\\d+ [a-z]+ \\d{4} \\d+:\\d+:\\d+ [-\\+]\\d+");
				safeDateTime = ToSafeDateTime(regex.Match(dateTime).Value);
			}
			else
			{
				safeDateTime = nullable;
			}
			return safeDateTime;
		}

		public static List<dynamic> ToValueTextItems(this Enum value, string emptyItem = "")
		{
			return ToValueTextItems(value.GetType(), emptyItem);
		}

		public static List<dynamic> ToValueTextItems(this Type enumType, string emptyItem = "")
		{
			List<object> objs;
			if ((enumType == null ? false : enumType.IsEnum))
			{
				List<object> objs1 = new List<object>();
				dynamic expandoObjects = new ExpandoObject();
				expandoObjects.Name = '1';
				if (!IsNullOrEmptyOrWhiteSpace(emptyItem))
				{
					expandoObjects = new ExpandoObject();
					expandoObjects.Text = emptyItem;
					expandoObjects.Value = -1;
					objs1.Add(expandoObjects);
				}
				foreach (int value in Enum.GetValues(enumType))
				{
					string description = GetDescription(((Enum)Enum.Parse(enumType, value.ToString())));
					if (!string.IsNullOrEmpty(description))
					{
						expandoObjects = new ExpandoObject();
						expandoObjects.Text = description;
						expandoObjects.Value = value;
						objs1.Add(expandoObjects);
					}
				}
				objs = objs1;
			}
			else
			{
				objs = null;
			}
			return objs;
		}

		public static string TrimEnd(this string value, string end, StringComparison comparison)
		{
			string str;
			if (IsInvalid(value))
			{
				str = value;
			}
			else if (IsInvalid(end))
			{
				str = value.TrimEnd(new char[0]);
			}
			else if (value.EndsWith(end, comparison))
			{
				int num = value.LastIndexOf(end, comparison);
				str = value.Substring(0, num);
			}
			else
			{
				str = value;
			}
			return str;
		}

		public static string TrimStart(this string value, string star)
		{
			string str;
			if (!IsInvalid(star))
			{
				str = (value.StartsWith(star) ? value.Substring(star.Length) : value);
			}
			else
			{
				str = value.TrimStart(new char[0]);
			}
			return str;
		}

		public static string UrlDecode(this string source, EnumEncodingType encodingType)
		{
			string empty;
			if (string.IsNullOrEmpty(source))
			{
				empty = string.Empty;
			}
			else
			{
				Encoding encoding = Encoding.GetEncoding(GetDescription(encodingType));
				empty = HttpUtility.UrlDecode(source, encoding);
			}
			return empty;
		}

		public static string UrlEncode(this string source, EnumEncodingType encodingType)
		{
			string empty;
			if (string.IsNullOrEmpty(source))
			{
				empty = string.Empty;
			}
			else
			{
				Encoding encoding = Encoding.GetEncoding(GetDescription(encodingType));
				empty = HttpUtility.UrlEncode(source, encoding);
			}
			return empty;
		}

		public static IQueryable<T> WhereIf<T>(this IQueryable<T> @this, Expression<Func<T, bool>> predicate, bool condition)
		{
			return (condition ? Queryable.Where(@this, predicate) : @this);
		}
	}
}